import { formatUnits, parseUnits, parseEther, formatEther } from "viem";
import BigNumber from "bignumber.js";
import { mainnet } from "wagmi/chains"; 

export const getMinForGas = (chainId: number) => {
  switch (chainId) {
    case mainnet.id:
      return parseEther("0.01");
    case parseInt(process.env.NEXT_PUBLIC_PRIVATE_CHAIN_ID as string):
      return parseEther("0.00001");
    default:
      return parseEther("0.00001");
  }
};

export const ellipseAddress = (
  address: string | null | undefined,
  width = 4
): string => {
  if (!address) {
    return "";
  }

  if (width === -1) {
    return address;
  }

  return `${address.slice(0, width)}...${address.slice(-width)}`;
};

export const displayBalance = (
  balance: bigint | string | number | undefined,
  decimals: number = 18,
  toFixed: number = 4
): string => {
  if (balance === undefined) return "---";
  return new BigNumber(balance + "")
    .dividedBy(new BigNumber("10").pow(decimals))
    .toFixed(toFixed, BigNumber.ROUND_DOWN);
};

export const trimBalance = (
  balance: string | number | undefined,
  fixed: number = 2
) => {
  if (!balance || balance === "NaN") {
    return new BigNumber("0").toFormat(fixed);
  }
  return new BigNumber(balance).toFormat(fixed, BigNumber.ROUND_DOWN);
};

export const getMaxValue = (
  balance: bigint | string | undefined,
  decimals: number = 18,
  toFixed: number = 9
): string => {
  if (!balance) return "0.000";
  // let value = new BigNumber(balance + "");
  // let number = new BigNumber("10").pow(decimals);
  // value = value.dividedBy(number);
  // return value.toFixed(toFixed, BigNumber.ROUND_DOWN);
  let resultValue = formatUnits(balance as bigint, decimals);
  return resultValue;
};

export const getETHMaxValue = (
  balance: bigint | undefined,
  chainId: number,
  decimals: number = 18
): string => {
  if (!balance) return "0.000";
  let minGas = getMinForGas(chainId);
  if (balance <= minGas) {
    return "0.000";
  }
  let value = balance - minGas;
  let resultValue = formatUnits(value, decimals);
  return resultValue;
};

export const Big0 = parseUnits("0", 1);
